package com.quectel.cms.controller.propertybill;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.propertybill.PropertyChargeableConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.propertybill.dto.PropertyChargeableItemDto;
import com.quectel.core.module.propertybill.dto.PropertyChargeableListItemBindingDto;
import com.quectel.core.module.propertybill.service.PropertyChargeableItemService;
import com.quectel.core.module.propertybill.service.PropertyChargeableListItemBindingService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/03/31 14:36
 */
@RestController
@RequestMapping("propertyChargeableItem")
@Tag(name = "PropertyChargeableItemController", description = "物业收费项目相关api")
public class PropertyChargeableItemController extends BaseController {

    @DubboReference
    private PropertyChargeableItemService propertyChargeableItemService;
    @DubboReference
    private PropertyChargeableListItemBindingService propertyChargeableListItemBindingService;

    @GetMapping("queryAllByChargeableListId")
    @Operation(summary = "查询标准绑定的收费项目列表")
    public Response<List<PropertyChargeableItemDto>> queryAllByChargeableListId(@RequestParam Long chargeableListId) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        List<PropertyChargeableItemDto> propertyChargeableItemDtos = new ArrayList<>();

        List<PropertyChargeableListItemBindingDto> propertyChargeableListItemBindingDtos
                = propertyChargeableListItemBindingService.queryList(request.getParams());
        if (CollectionUtils.isNotEmpty(propertyChargeableListItemBindingDtos)) {
            for (PropertyChargeableListItemBindingDto listItemBindingDto : propertyChargeableListItemBindingDtos) {
                Long chargeableItemId = listItemBindingDto.getChargeableItemId();
                PropertyChargeableItemDto propertyChargeableItemDto = propertyChargeableItemService.selectById(chargeableItemId);
                if (propertyChargeableItemDto != null) {
                    propertyChargeableItemDtos.add(propertyChargeableItemDto);
                }
            }
        }


        return Response.<List<PropertyChargeableItemDto>>ok().wrap(propertyChargeableItemDtos);
    }

    @GetMapping("queryAll")
    @Operation(summary = "不分页查询小区下的收费项目列表")
    public Response<List<PropertyChargeableItemDto>> queryAll(@RequestParam Long villageId) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        List<PropertyChargeableItemDto> propertyChargeableItemDtos
                = propertyChargeableItemService.queryList(request.getParams());

        return Response.<List<PropertyChargeableItemDto>>ok().wrap(propertyChargeableItemDtos);
    }

    /**
     * 物业收费项目作废操作
     */
    @PostMapping("cancel")
    @RequirePermissions(values = "propertyChargeableItem:cancel")
    @Operation(summary = "物业收费项目作废操作")
    public Response<Object> cancel(@RequestBody Long[] ids) {

        for (Long id : ids) {
            PropertyChargeableItemDto updately = new PropertyChargeableItemDto();
            updately.setId(id);
            updately.setStatus(PropertyChargeableConstant.StatusEnum.CANCEL.getType());
            propertyChargeableItemService.updateById(updately);

            Map<String, Object> sqlMap = new HashMap<>();
            sqlMap.put(LambdaUtil.getFieldName(PropertyChargeableListItemBindingDto::getChargeableItemId), id);
            List<PropertyChargeableListItemBindingDto> propertyChargeableListItemBindingDtos = propertyChargeableListItemBindingService.queryList(sqlMap);

            Long[] bindingIds = propertyChargeableListItemBindingDtos.stream()
                    .map(PropertyChargeableListItemBindingDto::getId)
                    .toArray(Long[]::new);
            // 删除绑定的标准和项目关系
            propertyChargeableListItemBindingService.deleteBatch(bindingIds);
        }
        return Response.ok();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "propertyChargeableItem:list")
    @Operation(summary = "分页获取物业收费项目列表")
    public Response<Page<PropertyChargeableItemDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = propertyChargeableItemService.queryTotal(request.getParams());

        List<PropertyChargeableItemDto> list = null;
        if (total > 0) {
            list = propertyChargeableItemService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PropertyChargeableItemDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PropertyChargeableItemDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "propertyChargeableItem:edit")
    @Operation(summary = "在编辑时根据id查询物业收费项目详情")
    public Response<PropertyChargeableItemDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (propertyChargeableItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PropertyChargeableItemDto propertyChargeableItemDto = propertyChargeableItemService.selectById(id);

        return Response.<PropertyChargeableItemDto>ok().wrap(propertyChargeableItemDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "propertyChargeableItem:info")
    @Operation(summary = "根据id查询物业收费项目的详情")
    public Response<PropertyChargeableItemDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (propertyChargeableItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PropertyChargeableItemDto propertyChargeableItemDto = propertyChargeableItemService.selectById(id);

        return Response.<PropertyChargeableItemDto>ok().wrap(propertyChargeableItemDto);
    }

    /**
     * 保存
     *
     * @param propertyChargeableItemDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "propertyChargeableItem:edit")
    @Operation(summary = "新增物业收费项目")
    public Response<Object> save(@RequestBody @Validated PropertyChargeableItemDto propertyChargeableItemDto) {

        //填充基础数据
        fillSaveCommonData(propertyChargeableItemDto);

        // 校验是否存在记录
        PropertyChargeableItemDto dbValue=
                propertyChargeableItemService.selectOne(propertyChargeableItemDto.getVillageId(), propertyChargeableItemDto.getName());
        if (dbValue != null){
            return Response.error("同一小区下不允许名称重复");
        }

        propertyChargeableItemService.save(propertyChargeableItemDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param propertyChargeableItemDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "propertyChargeableItem:edit")
    @Operation(summary = "根据id修改物业收费项目")
    public Response<Object> update(@RequestBody @Validated PropertyChargeableItemDto propertyChargeableItemDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(propertyChargeableItemDto.getId()));
        if (propertyChargeableItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(propertyChargeableItemDto);

        propertyChargeableItemService.updateById(propertyChargeableItemDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "propertyChargeableItem:delete")
    @Operation(summary = "根据多条记录id批量删除物业收费项目")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (propertyChargeableItemService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        propertyChargeableItemService.deleteBatch(ids);

        return Response.ok();
    }
}
